import os
from PIL import Image
from flask import current_app
from werkzeug.utils import secure_filename
import time

ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
UPLOAD_FOLDER = 'app/static/uploads'
MAX_SIZE = (800, 800)  # 最大图片尺寸

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

def save_image(file, folder_name):
    """保存并处理上传的图片"""
    if file and allowed_file(file.filename):
        # 生成安全的文件名
        filename = secure_filename(file.filename)
        timestamp = int(time.time())
        unique_filename = f"{folder_name}_{timestamp}_{filename}"
        
        # 确保上传目录存在
        upload_path = os.path.join(UPLOAD_FOLDER, folder_name)
        if not os.path.exists(upload_path):
            os.makedirs(upload_path)
            
        file_path = os.path.join(upload_path, unique_filename)
        
        # 保存并处理图片   QQ:575732022
        try:
            image = Image.open(file)
            
            # 转换为RGB模式（处理PNG等格式）
            if image.mode != 'RGB':
                image = image.convert('RGB')
                
            # 调整图片大小
            if image.size[0] > MAX_SIZE[0] or image.size[1] > MAX_SIZE[1]:
                image.thumbnail(MAX_SIZE, Image.LANCZOS)
                
            # 保存处理后的图片
            image.save(file_path, quality=85, optimize=True)
            
            # 返回相对路径
            return f'/static/uploads/{folder_name}/{unique_filename}'
            
        except Exception as e:
            print(f"Error processing image: {e}")
            return None
            
    return None

def delete_file(file_path):
    """删除文件"""
    if file_path:
        try:
            full_path = os.path.join('app/static', file_path.lstrip('/static/'))
            if os.path.exists(full_path):
                os.remove(full_path)
                return True
        except Exception as e:
            print(f"Error deleting file: {e}")
    return False 